<template>
  <div class="cabinet-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span>柜子管理</span>
      </div>

      <!-- 添加功能表格 -->
      <el-table :data="addTableData" border style="margin-bottom: 20px; width: 100%;"
        :row-class-name="addTableRowClass">
        <el-table-column prop="label" label="功能" width="120" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <template v-if="scope.row.key === 'area'">
              <el-input v-model="areaForm.area" placeholder="请输入区域编号" style="width: 220px; margin-right: 16px;" />
              <el-button type="primary" @click="handleAddArea">添加区域</el-button>
            </template>
            <template v-else-if="scope.row.key === 'row'">
              <el-select v-model="areaForm.selectedArea" placeholder="请选择区域" style="width: 140px; margin-right: 16px;">
                <el-option v-for="area in areas" :key="area" :label="area" :value="area" />
              </el-select>
              <el-input v-model="areaForm.row" placeholder="请输入排号" style="width: 140px; margin-right: 16px;" />
              <el-button type="primary" @click="handleAddRow">添加排</el-button>
            </template>
            <template v-else-if="scope.row.key === 'cabinet'">
              <el-select v-model="cabinetForm.area" placeholder="请选择区域" style="width: 140px; margin-right: 16px;">
                <el-option v-for="area in areas" :key="area" :label="area" :value="area" />
              </el-select>
              <el-select v-model="cabinetForm.row" placeholder="请选择排" style="width: 140px; margin-right: 16px;">
                <el-option v-for="row in rows[cabinetForm.area]" :key="row" :label="row" :value="row" />
              </el-select>
              <el-input v-model.number="cabinetForm.number" placeholder="请输入增加的个数" style="width: 180px; margin-right: 16px;" />
              <el-button type="primary" @click="handleAddCabinetBatch">批量添加柜子</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 检索 -->
      <el-row :gutter="0" class="mb-20 left-align-form">
        <el-form :model="searchForm" @submit.native.prevent label-width="auto" style="display: flex; align-items: center;">
           <el-form-item label="" style="margin-bottom: 0; display: flex; align-items: center;">
             <i class="el-icon-search" style="font-size: 18px; color: #909399; margin-right: 8px;"></i>
             <el-input v-model="searchForm.keyword" placeholder="输入区域、排、编号或状态进行检索" style="width: 260px;" />
           </el-form-item>
        </el-form>
      </el-row>

      <!-- 柜子列表 -->
      <el-table :data="cabinetsList" style="width: 100%">
        <el-table-column prop="id" label="柜子编号" width="180" />
        <el-table-column prop="area" label="区域" width="100" />
        <el-table-column prop="row" label="排" width="100" />
        <el-table-column prop="number" label="柜号" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button
                type="danger"
                size="mini"
                @click="handleRemoveCabinet(scope.row)"
                :disabled="scope.row.status === 'in_use'"
              >
                删除
              </el-button>
              <el-button
                type="warning"
                size="mini"
                @click="handleReleaseCabinet(scope.row)"
                v-if="scope.row.status === 'in_use'"
              >
                释放
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCabinets"
      />
    </el-card>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

export default {
  name: "CabinetManagement",
  data() {
    return {
      areaForm: {
        area: "",
        selectedArea: "",
        row: ""
      },
      cabinetForm: {
        area: "",
        row: "",
        number: null
      },
      // 新增：添加功能表格数据
      addTableData: [
        { key: 'area', label: '添加区域' },
        { key: 'row', label: '添加排' },
        { key: 'cabinet', label: '添加柜子' }
      ],
      // 分页相关数据
      pageSize: 10,
      currentPage: 1,
      searchForm: {
        keyword: ''
      }
    };
  },
  computed: {
    ...mapState({
      areas: (state) => state.cabinets.areas,
      rows: (state) => state.cabinets.rows
    }),
    ...mapGetters(["getCabinetsByArea", "getAllCabinets"]),
    cabinetsList() {
      // Start with all cabinets
      let sortedCabinets = [...this.getAllCabinets]; // Create a mutable copy

      // Sort cabinets by area, then row, then number
      sortedCabinets.sort((a, b) => {
        // Sort by area
        if (a.area < b.area) return -1;
        if (a.area > b.area) return 1;

        // If areas are the same, sort by row (convert to number for correct sorting)
        const rowA = parseInt(a.row);
        const rowB = parseInt(b.row);
        if (rowA < rowB) return -1;
        if (rowA > rowB) return 1;

        // If area and row are the same, sort by number (convert to number)
        const numberA = parseInt(a.number);
        const numberB = parseInt(b.number);
        if (numberA < numberB) return -1;
        if (numberA > numberB) return 1;

        return 0; // Objects are equal
      });

      // Apply search filter
      const filteredCabinets = sortedCabinets.filter(cabinet =>
        Object.values(cabinet).some(value =>
          String(value).toLowerCase().includes(this.searchForm.keyword.toLowerCase())
        )
      );

      // 应用分页
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return filteredCabinets.slice(start, end);
    },
    totalCabinets() {
      // 计算过滤后的总数，用于分页
      const filteredCabinets = this.getAllCabinets.filter(cabinet =>
        Object.values(cabinet).some(value =>
          String(value).toLowerCase().includes(this.searchForm.keyword.toLowerCase())
        )
      );
      return filteredCabinets.length;
    }
  },
  mounted() {
    console.log('CabinetManagement.vue mounted');
    console.log('Store cabinets data:', this.$store.state.cabinets.cabinets);
    console.log('Cabinets list computed:', this.cabinetsList);
    console.log('[CabinetManagement] areas:', this.areas);

    // 尝试刷新 el-select 的 placeholder 显示
    if (this.areas && this.areas.length > 0 && this.cabinetForm.area === '') {
      const currentArea = this.cabinetForm.area;
      this.cabinetForm.area = null; // temporarily set to null
      this.$nextTick(() => {
        this.cabinetForm.area = currentArea; // restore to original empty string
      });
    }
  },
  watch: {
    'cabinetForm.area': function(newArea, oldArea) {
      if (newArea !== oldArea) {
        this.cabinetForm.row = ""; // Reset row when area changes
      }
    },
  },
  methods: {
    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 修改每页大小时重置到第一页
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    getStatusText(status) {
      const statusMap = {
        available: "空闲",
        in_use: "使用中",
        maintenance: "维修中"
      };
      return statusMap[status] || status;
    },
    getStatusType(status) {
      const typeMap = {
        available: "success",
        in_use: "info",
        maintenance: "danger"
      };
      return typeMap[status] || "info";
    },
    async handleAddArea() {
      if (!this.areaForm.area) {
        this.$message.warning("请输入区域编号");
        return;
      }
      try {
        await this.$store.dispatch("addArea", this.areaForm.area);
        this.$message.success("添加区域成功");
        this.areaForm.area = "";
      } catch (error) {
        this.$message.error(error.message || "添加区域失败");
      }
    },
    async handleAddRow() {
      if (!this.areaForm.selectedArea || !this.areaForm.row) {
        this.$message.warning("请选择区域并输入排号");
        return;
      }
      try {
        await this.$store.dispatch("addRow", {
          area: this.areaForm.selectedArea,
          row: this.areaForm.row
        });
        this.$message.success("添加排成功");
        this.areaForm.row = "";
      } catch (error) {
        this.$message.error(error.message || "添加排失败");
      }
    },
    async handleAddCabinetBatch() {
      const area = this.cabinetForm.area;
      const row = this.cabinetForm.row;
      const count = this.cabinetForm.number; // Get the count from input

      if (!area || !row) {
        this.$message.warning("请选择区域和排号");
        return;
      }

      // Validate count input
      if (typeof count !== 'number' || count <= 0 || !Number.isInteger(count)) {
          this.$message.warning("请输入有效的正整数作为增加的个数");
          return;
      }

      // Calculate the starting number (next available)
      const cabinetsInRow = this.getAllCabinets.filter(cabinet =>
          cabinet.area === area && cabinet.row === row
      );

      const startNumber = cabinetsInRow.length === 0
          ? 1
          : Math.max(...cabinetsInRow.map(cabinet => parseInt(cabinet.number))) + 1;

      let addedCount = 0;
      let failedCount = 0;
      let lastAddedId = '';

      for (let i = 0; i < count; i++) {
          const currentNumber = startNumber + i;
          const cabinetId = `${area}-${row}-${currentNumber}`;

          // Check if cabinet already exists before attempting to add
          if (this.$store.state.cabinets.cabinets[cabinetId]) {
              this.$message.warning(`柜子 ${cabinetId} 已存在，停止批量添加`);
              failedCount = count - i; // Count remaining as failed
              break; // Stop adding if a duplicate is found
          }

          try {
              // Dispatch action to add a single cabinet
              await this.$store.dispatch("addCabinet", {
                  area: area,
                  row: row,
                  number: currentNumber
              });
              addedCount++;
              lastAddedId = cabinetId;
          } catch (error) {
              failedCount++;
          }
      }

      if (addedCount > 0) {
          this.$message.success(`成功添加了 ${addedCount} 个柜子，最后一个柜子编号为 ${lastAddedId}`);
      }

      if (failedCount > 0) {
          this.$message.error(`添加柜子时发生错误，成功添加 ${addedCount} 个，失败 ${failedCount} 个`);
      }
    },
    addTableRowClass() {
      return 'add-table-row-bg';
    },
    async handleRemoveCabinet(cabinet) {
      try {
        await this.$confirm('确定要删除这个柜子吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await this.$store.dispatch("removeCabinet", cabinet.id);
        this.$message.success("删除成功");
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || "删除失败");
        }
      }
    },
    async handleReleaseCabinet(cabinet) {
      try {
        await this.$confirm('确定要释放这个柜子吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await this.$store.dispatch("releaseCabinet", { cabinetId: cabinet.id });
        this.$message.success("释放成功");
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || "释放失败");
        }
      }
    }
  }
};
</script>

<style scoped>
.cabinet-management {
  padding: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}

.left-align-form {
  margin-bottom: 20px;
}

.add-table-row-bg {
  background-color: #f5f7fa;
}
</style>